package com.example.mycloudpicture.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.mycloudpicture.exception.BusinessException;
import com.example.mycloudpicture.exception.ErrorCode;
import com.example.mycloudpicture.exception.ThrowUtils;
import com.example.mycloudpicture.model.dto.space.SpaceAddRequest;
import com.example.mycloudpicture.model.dto.space.SpaceQueryRequest;
import com.example.mycloudpicture.model.entity.Space;
import com.example.mycloudpicture.model.entity.User;
import com.example.mycloudpicture.model.enums.SpaceLevelEnum;
import com.example.mycloudpicture.model.vo.SpaceVo;
import com.example.mycloudpicture.model.vo.UserVo;
import com.example.mycloudpicture.service.SpaceService;
import com.example.mycloudpicture.mapper.SpaceMapper;
import com.example.mycloudpicture.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;


/**
* @author 黄宽亮
* @description 针对表【space(空间)】的数据库操作Service实现
* @createDate 2025-02-25 18:14:30
*/
@Service
public class SpaceServiceImpl extends ServiceImpl<SpaceMapper, Space>
    implements SpaceService{

    @Resource
    UserService userService;
    @Resource
    TransactionTemplate transactionTemplate;
    @Override
    public long addSpace(SpaceAddRequest spaceAddRequest, User loginUser) {
        ThrowUtils.throwIf(spaceAddRequest==null, ErrorCode.PARAMS_ERROR);
        //校验空间信息
        Space space = new Space();
        BeanUtils.copyProperties(spaceAddRequest, space);
        if(StrUtil.isBlank(space.getSpaceName())){
            space.setSpaceName("默认空间");
        }
        if(space.getSpaceLevel()==null){
            space.setSpaceLevel(SpaceLevelEnum.COMMON.getValue());
        }
        //填充容量和大小
        this.fillSpaceBySpaceLevel(space);
        this.validSpace(space, true);
        Long userId=loginUser.getId();
         space.setUserId(userId);
        if(SpaceLevelEnum.COMMON.getValue()!=space.getSpaceLevel()&&!userService.isAdmin(loginUser)){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"非管理员无法创建高级空间");
        }
        String lock=String.valueOf(userId).intern();
        synchronized(lock){
            Long newSpaceId = transactionTemplate.execute(status -> {
                boolean exist = this.lambdaQuery()
                        .eq(Space::getUserId, userId)
                        .exists();
                ThrowUtils.throwIf(exist, ErrorCode.PARAMS_ERROR, "用户已存在空间");
                boolean result=this.save(space);
                ThrowUtils.throwIf(!result, ErrorCode.PARAMS_ERROR, "创建失败");
                return space.getId();
            });
            return Optional.ofNullable(newSpaceId).orElse(-1L);
        }
    }

    @Override
    public void validSpace(Space space, boolean add) {
        ThrowUtils.throwIf(space==null, ErrorCode.PARAMS_ERROR);
        //从对象中取值
        String spaceName = space.getSpaceName();
        Integer spaceLevel = space.getSpaceLevel();
        SpaceLevelEnum enumByValue = SpaceLevelEnum.getEnumByValue(spaceLevel);
        //创建时校验
        if(add){
            if(StrUtil.isBlank(spaceName)){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间名不能为空");
            }
            if(spaceLevel==null){
                throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间等级不能为空");
            }
        }
        //修改数据时，空间名称进行校验
        if(StrUtil.isNotBlank(spaceName)&&spaceName.length()>30){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间名称过长");
        }
        if(spaceLevel!=null&&enumByValue==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"空间等级不存在");
        }
    }

    @Override
    public SpaceVo getSpaceVO(Space space, HttpServletRequest request) {
        //对象转换类
        SpaceVo spaceVo = SpaceVo.objToVo(space);
        //关联查询用户信息
        Long userId=space.getUserId();
        if(userId!=null&&userId>0){
            User user = userService.getById(userId);
            UserVo userVo=userService.getUserVo(user);
            spaceVo.setUser(userVo);
        }
        return spaceVo;
    }

    @Override
    public Page<SpaceVo> getSpaceVOPage(Page<Space> spacePage, HttpServletRequest request) {
        List<Space> spaceList=spacePage.getRecords();
        Page<SpaceVo> spaceVoPage =new Page<>(spacePage.getCurrent(),spacePage.getSize(),spacePage.getTotal());
        if(CollUtil.isEmpty(spaceList)){
            return spaceVoPage;
        }
        //对象列表 => 封装对象列表
        List<SpaceVo> spaceVoList = spaceList.stream().map(SpaceVo::objToVo).collect(Collectors.toList());
        //关联查询用户信息
        Set<Long> userIdSet = spaceList.stream().map(Space::getUserId).collect(Collectors.toSet());
        Map<Long,List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream().collect(Collectors.groupingBy(User::getId));
        //封装用户信息
        spaceVoList.forEach(spaceVo -> {
            Long userId=spaceVo.getUserId();
            User user=null;
            if(userIdUserListMap.containsKey(userId)){
                user=userIdUserListMap.get(userId).get(0);
            }
            spaceVo.setUser(userService.getUserVo(user));
        });
        spaceVoPage.setRecords(spaceVoList);
        return spaceVoPage;
    }

    @Override
    public QueryWrapper<Space> getQueryWrapper(SpaceQueryRequest spaceQueryRequest) {
        QueryWrapper<Space> queryWrapper = new QueryWrapper<>();
        if(spaceQueryRequest==null){
            return queryWrapper;
        }
        //从对象中取值
        Long id = spaceQueryRequest.getId();
        Long userId = spaceQueryRequest.getUserId();
        String spaceName = spaceQueryRequest.getSpaceName();
        Integer spaceLevel = spaceQueryRequest.getSpaceLevel();
        Integer spaceType = spaceQueryRequest.getSpaceType();
        int current = spaceQueryRequest.getCurrent();
        int pageSize = spaceQueryRequest.getPageSize();
        String sortField = spaceQueryRequest.getSortField();
        String sortOrder = spaceQueryRequest.getSortOrder();
        //拼接查询条件
        queryWrapper.eq(ObjUtil.isNotEmpty(id),"id",id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId),"userId",userId);
        queryWrapper.like(StrUtil.isNotBlank(spaceName),"spaceName",spaceName);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceLevel),"spaceLevel",spaceLevel);
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), "ascend".equals(sortOrder),sortField);
        return queryWrapper;
    }

    @Override
    public void fillSpaceBySpaceLevel(Space space) {
        SpaceLevelEnum spaceLevelEnum=SpaceLevelEnum.getEnumByValue(space.getSpaceLevel());
        if(spaceLevelEnum!=null){
            long maxSize=spaceLevelEnum.getMaxSize();
            if(space.getMaxSize()==null){
                space.setMaxSize(maxSize);
            }
            long maxCount=spaceLevelEnum.getMaxCount();
            if(space.getMaxCount()==null){
                space.setMaxCount(maxCount);
            }
        }
    }

    @Override
    // 重写父类方法，用于检查用户是否有权限访问指定空间
    public void checkSpaceAuth(User loginUser, Space space) {
        // 仅本人或管理员可编辑
        if (!space.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }
}




